package controllers

import (
	"Blog/models"
	"bytes"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	beego "github.com/beego/beego/v2/server/web"
)

type NodeController struct{
	 BaseController
}
func (c *NodeController) NestPrepare(){
	c.MustLogin()
	//if c.User.Role!=0{
	//	fmt.Println(c.User)
	//	c.Abort500(errors.New("用户权限不足"))
	//}
}
func (c *NodeController) Index(){
	c.Data["key"]=c.UUID()
	c.TplName="node_text.html"
}
func (c *NodeController) Save(){
	if c.Ctx.Input.IsPost(){
		var node models.Node
		key:=c.Ctx.Input.Params()  //路由设置的时候可以设置参数，可以获取相关的参数
        title:=c.JugeNull("title","标题不能为空")
        content:=c.JugeNull("content","文章不能为空")
        num,node,err:=models.QueryNodeByKey(key["0"])  //通过key查询是否存在
		if num!=0{   //存在文章
				node.Title=title
				node.Content=content
			}else {     //没有这篇文章
					node.UserId=int(c.User.ID)
					node.Uuid=key["0"]
					node.Title=title
					node.Content=content
			}
		htmlstr,err:=getSummary(content)
		if err!=nil{
			c.Abort500(err)
		}
		fmt.Println(htmlstr)
		node.Summary=htmlstr   //将摘要赋值
		err=models.SaveNode(node)
		if err!=nil{
			c.Abort500(err)
		}
		c.Data["json"]=map[string]interface{}{
			"code":0,
			"action":"/auth/index",
		}
		_ = c.ServeJSON()
	}
}
func (c *NodeController)Details(){
	key:=c.GetString("key")
	_,node,err:=models.QueryNodeByKey(key)
	if err!=nil{
       c.Abort500(err)
	}
	_,messages,err:=models.QueryMessageByKey(key)
	if err!=nil{
		c.Abort500(err)
	}
	c.Data["Role"]=c.User.Role
	c.Data["messages"]=messages
	c.Data["node"]=node
	c.TplName="details.html"
}
func (c *NodeController) Edit(){
	key:=c.GetString("key")
	node,err:=models.QueryNodeByUserIdAndKey(int(c.User.ID),key)
	if err!=nil{
		c.Abort500(err)
	}
	c.Data["node"]=node
	c.TplName="edit.html"
}
func (c *NodeController) Del(){
	key:=c.GetString("key")   //获取key值
	userid:=c.User.ID
    err:=models.DeleteNode(key,int(userid))
    if err!=nil{
    	c.Abort500(err)
	}
	c.Redirect(beego.URLFor("AuthController.Index"),302)
}
//使用goquery获取摘要
func getSummary(html string)(string,error){
	var buf bytes.Buffer
	if _,err:=buf.Write([]byte(html));err!=nil{
       return "",err
	}
	doc,err:=goquery. NewDocumentFromReader(&buf)
	if err!=nil{
		return "",err
	}
	htmlstr:=doc.Find("p").Text()//获取p标签下的文档
	if len(htmlstr)>100{
		htmlstr=htmlstr[:100]
	}
	return htmlstr,nil
}

func (c *NodeController) AddPraise(){
	  key:=c.GetString("ID")
	  fmt.Println("得到的",key)
}

